package com.meixiang.fragment.fund;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.R;
import com.meixiang.activity.WebviewActivity;
import com.meixiang.activity.account.myfund.MyFundActivity;
import com.meixiang.adapter.myFundAdapter.FundOptionalAdapter;
import com.meixiang.dialog.LoadingDialog;
import com.meixiang.dialog.OptionalScreenPopup;
import com.meixiang.entity.fund.FundOptionalBean;
import com.meixiang.entity.fund.FundOptionalResult;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.tool.FundAnimationTool;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.DensityUtil;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 自选基金
 * Created by xyj on 2016/5/31.
 */
public class OptionalFragment extends BaseFragment implements View.OnClickListener, OptionalScreenPopup.IOnSubmitClickListener, OnRefreshListener {

    public static final int REQUEST_CODE = 0x001;
    private Context context;
    @Bind(R.id.swipe_target)
    RecyclerView mRecycler;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mLayout;
    @Bind(R.id.rl_newest_price)
    RelativeLayout rl_newest_price; //最新价
    @Bind(R.id.iv_newest_price_sort)
    ImageView iv_newest_sort;  //对应图片
    @Bind(R.id.rl_amount_increase)
    RelativeLayout rl_amount_increase; //日涨幅
    @Bind(R.id.tv_day_price_amount_increase)
    TextView amount_increase;
    @Bind(R.id.iv_amount_increase_sort)
    ImageView iv_amount_increase_sort; //日涨幅对应图片
    @Bind(R.id.ll_optional_top_view)
    LinearLayout ll_optional_top_view;
    private FundOptionalAdapter mAdapter;
    private OptionalScreenPopup mPopup;
    private View rootView;
    private float moveToCenter;
    private int clickNum = 0; //记录点击的次数
    private boolean isThree = false; //是否点击了 3次
    private int page = 1;
    private int pageSize = 10;
    private static ArrayList<FundOptionalBean> fund_select_list = new ArrayList<>();
    private int type = 0; //排序类型 0日涨幅，1近一周，2近一个月，3近三个月，4近六个月,5近一年， 6今年来 默认为：0
    private int rank_type = 0; // 排序 0默认排序，1从高到低，2从低到高 默认为：0
    private int rank_key_type = 0; //净值排序 0默认排序，1从高到低，2从低到高 默认为：0
    private LoadingDialog loadingDialog;
    private int index =0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            fund_select_list = getArguments().getParcelableArrayList("optionList");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_optional_content, container, false);
        ButterKnife.bind(this, rootView);
        context = getActivity();
        return rootView;
    }

    @Override
    protected void initTitle() {
    }

    @Override
    protected void initView() {
        FundAnimationTool.initAnimation(); //初始化左移动画
        /**
         * 计算平移的距离
         */
        this.moveToCenter = (1.0F * (Tool.getWindowWith(getContext()) / 2 - this.rl_amount_increase.getMeasuredWidth() / 2 - DensityUtil.dip2px(getActivity(), 50.0F)) / Tool.getWindowWith(getContext()));
        rl_newest_price.setOnClickListener(this);
        rl_amount_increase.setOnClickListener(this);
        mLayout.setOnRefreshListener(this);
        mLayout.setLoadMoreEnabled(false);
    }

    @Override
    protected void setData() {
        loadingDialog = new LoadingDialog(getContext());
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        mRecycler.setLayoutManager(mLayoutManager);
        mRecycler.setItemAnimator(new DefaultItemAnimator());
        initOptionalFund();
        if (fund_select_list == null) {
            getHttpFundData();
        } else {
            mAdapter.refreshIndex(index);
            mAdapter.refreshData(fund_select_list);
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 填充Adapter
     */
    private void initOptionalFund() {
        mAdapter = new FundOptionalAdapter(context);
        mRecycler.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(context, WebviewActivity.class);
                if("".equals(fund_select_list.get(position).getUrl())||null == fund_select_list.get(position).getUrl()){
                    intent.putExtra("url",Config.FUND_INFO_NEW + "?fund_id=" + fund_select_list.get(position).getFund_id());
                }else{
                    intent.putExtra("url", fund_select_list.get(position).getUrl());
                }
                intent.putExtra("title", fund_select_list.get(position).getFund_name());
                context.startActivity(intent);
            }
        });
    }

    /**
     * 获取我的自选基金数据
     * fundSessionId 我的基金sessionId
     */
    private void getHttpFundData() {
        HttpParams params = new HttpParams();
        params.put("page", String.valueOf(page));
        params.put("pageSize", String.valueOf(pageSize));
        HttpUtils.post(Config.FUN_ACCOUNT_TYPE2, MyFundActivity.TAG,params, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                FundOptionalResult fundOptionalResult = AbJsonUtil.fromJson(result.optString("data").toString(), new TypeToken<FundOptionalResult>() {
                });
                if (fundOptionalResult != null && fundOptionalResult.getFund_select_list() != null) {
                    fund_select_list = fundOptionalResult.getFund_select_list();
                    mAdapter.refreshIndex(index);
                    mAdapter.refreshData(fund_select_list);
                    mLayout.setRefreshing(false);
                }
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                if (loadingDialog != null && loadingDialog.isShowing())
                    loadingDialog.dismiss();
            }

            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                if (loadingDialog != null && !loadingDialog.isShowing())
                    loadingDialog.show();
            }

            @Override
            public void onError(String code, String message) {
                if ("-2".equals(code)) {// 表示未登录 需要跳转到口袋登录页面
                    getHttpToLogin();
                }
            }
        });
    }

    /***
     * toLogin 跳转登录或者注册界面API
     * url 回调地址
     */
    public void getHttpToLogin() {
        HttpParams params = new HttpParams();
        params.put("url", Config.CALLBACK_URL);
        HttpUtils.post(Config.FUND_TOLOGIN, MyFundActivity.TAG,params, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Intent intent = new Intent(context, WebviewActivity.class);
                intent.putExtra("resultUrl", result.optString("url"));
                startActivityForResult(intent, 100);
            }

            @Override
            public void onError(String code, String message) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getHttpFundData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_newest_price:
                clickNum++;
                if (!isThree) {
                    changeBgImage(clickNum, iv_newest_sort);
                }
                if (fund_select_list != null) {
                    Tool.listSort(rank_key_type, rank_type, type, fund_select_list);
                    mAdapter.refreshIndex(type);
                    mAdapter.notifyDataSetChanged();
                }
                break;

            case R.id.rl_amount_increase: //点击日涨幅控件
                showSortPopupWindow();
                break;
        }
    }

    /**
     * 更改图标样式
     */
    private void changeBgImage(int number, ImageView imageView) {
        switch (number) {
            case 1:
                rank_key_type = 1;
                rank_type = 1;
                imageView.setImageResource(R.mipmap.sort1);
                break;
            case 2:
                rank_key_type = 2;
                rank_type = 2;
                imageView.setImageResource(R.mipmap.sort2);
                break;
            case 3:
                rank_key_type = 0;
                rank_type = 0;
                imageView.setImageResource(R.mipmap.sort3);
                clickNum = 0;
                break;
        }
    }

    /**
     * 展示层的动画和左右移动的动画
     */
    protected void showSortPopupWindow() {
        if (this.mPopup == null)
            initPupopWindow();
        this.mPopup.setOutDissmissListener(new PopupWindow.OnDismissListener() {
            public void onDismiss() { //当popu窗口关闭时开始执行复原动画
                OptionalFragment.this.ll_optional_top_view.startAnimation(FundAnimationTool.left_disAnimation);
                OptionalFragment.this.rl_amount_increase.startAnimation(FundAnimationTool.right_disAnimation);
            }
        });
        FundAnimationTool.initAniMation(moveToCenter);
        this.mPopup.startShowAnimation();
        this.mPopup.showAsDropDown(this.ll_optional_top_view);
        this.mPopup.setSubmitClickListener(this);
        this.ll_optional_top_view.startAnimation(FundAnimationTool.left_showAnimation);
        this.rl_amount_increase.startAnimation(FundAnimationTool.right_showAnimation);
        FundAnimationTool.right_showAnimation.setFillAfter(true);
        FundAnimationTool.left_showAnimation.setFillAfter(true);
    }

    public static ArrayList<FundOptionalBean> getOptionList() {
        return fund_select_list;
    }

    /**
     * 初始化PopupWindow层
     */
    private void initPupopWindow() {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_optional_screen_view, null);
        mPopup = new OptionalScreenPopup(context, view, rootView.getLayoutParams().height);
    }

    @Override
    public void onClick(int selectPos, int rank_type, String titleName) {
        this.type = selectPos;
        this.rank_type = rank_type;
        amount_increase.setText(titleName);
        changeBgImage(3, iv_newest_sort);
        changeBgImage(rank_type, iv_amount_increase_sort);
        if (fund_select_list != null) {
            Tool.listSort(0, rank_type, type, fund_select_list);
            mAdapter.notifyDataSetChanged();
            mAdapter.refreshIndex(type);
        }
    }

    public OptionalFragment getIntence(Bundle bundle) {
        OptionalFragment optionalFragment = new OptionalFragment();
        optionalFragment.setArguments(bundle);
        return optionalFragment;
    }

    @Override
    public void onRefresh() {
        page = 1;
        getHttpFundData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
